package cn.darkhorse.ticket.production.service.impl;

import cn.darkhorse.exception.ServiceException;
import cn.darkhorse.ticket.constants.TicketConstants;
import cn.darkhorse.ticket.production.dao.TicketTaskDao;
import cn.darkhorse.ticket.production.mapper.TicketTaskMapper;
import cn.darkhorse.ticket.production.pojo.BatchPersons;
import cn.darkhorse.ticket.production.pojo.TicketTask;
import cn.darkhorse.ticket.production.service.BatchPersonsDTO;
import cn.darkhorse.ticket.production.service.TicketTaskService;
import cn.darkhorse.ticket.production.vo.TicketTaskListVO;
import cn.darkhorse.ticket.production.vo.TicketTaskScheduleVO;
import cn.darkhorse.ticket.production.vo.TicketTaskViewVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 工序任务 服务实现类
 * </p>
 *
 * @author wangxinghui
 * @since 2024-01-30
 */
@Service
public class TicketTaskServiceImpl extends ServiceImpl<TicketTaskMapper, TicketTask> implements TicketTaskService {
	
	@Resource
	private TicketTaskDao ticketTaskDao;
	
	/**
	 * 列表
	 * @param taskDTO
	 * @return
	 */
	@Override
	public List<TicketTaskListVO> list(TicketTaskDTO taskDTO) {
		List<TicketTaskListVO> voList = ticketTaskDao.list(taskDTO);
		//TODO 计算数据
		return voList;
	}
	
	
	@Override
	public void add(List<TicketTask> ticketTask) {
	
		saveBatch(ticketTask);
		
	}
	
	@Override
	public List<TicketTaskListVO> viewOfTicketInfo(String ticketCode) {
		TicketTaskDTO taskDTO = new TicketTaskDTO();
		taskDTO.setTicketCode(ticketCode);
		List<TicketTaskListVO> voList = ticketTaskDao.list(taskDTO);
		Collections.sort(voList, new Comparator<TicketTaskListVO>() {
			@Override
			public int compare(TicketTaskListVO o1, TicketTaskListVO o2) {
				return o1.getOrderNumber() - o2.getOrderNumber(); //按从小到大排序
			}
		});
		return voList;
	}
	
	@Override
	public Map<String,List<TicketTaskScheduleVO>> viewOfTaskSchedule(List<String> ticketCodes) {
		Map<String,List<TicketTaskScheduleVO>> maps = new HashMap<>();
		LambdaQueryWrapper<TicketTask> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(TicketTask::getTicketInfoCode,ticketCodes);
		queryWrapper.orderByAsc(TicketTask::getTicketInfoCode).orderByAsc(TicketTask::getOrderNumber);
		List<TicketTask> taskList = list(queryWrapper);
		taskList.forEach(item->{
			TicketTaskScheduleVO scheduleVO = new TicketTaskScheduleVO();
			List<TicketTaskScheduleVO> voList = maps.get(item.getTicketInfoCode());
			if(null == voList){
				voList = new ArrayList<>();
				maps.put(item.getTicketInfoCode(),voList);
			}
			scheduleVO.setProcedureName(item.getProcedureName());
			scheduleVO.setOrderNumber(item.getOrderNumber());
			voList.add(scheduleVO);
		});
		return maps;
	}
	
	@Override
	public TicketTaskViewVO view(Long id) {
		TicketTaskViewVO vo = ticketTaskDao.view(id);
		return vo;
	}
	
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void batchPersons(BatchPersonsDTO personsDTO,String tableName) {
		List<Long> taskIds = personsDTO.getTaskIds();
		if(personsDTO.getUserIds().isEmpty()){
		    return;
		}
		//校验不能操作的任务
		boolean b = inoperableTask(taskIds);
		if(b){
			throw new ServiceException("已经结束或取消的不能进行设置权限人！");
		}
		List<BatchPersons> personsList = new ArrayList<>();
		taskIds.forEach(tt->{
			personsDTO.getUserIds().forEach(tp->{
				BatchPersons persons = new BatchPersons();
				persons.setTaskId(tt);
				persons.setUserId(tp);
				personsList.add(persons);
			});
		});
		ticketTaskDao.deletePersons(tableName,taskIds);
		ticketTaskDao.batchPersons(tableName,personsList);
	}
	
	@Override
	public void modifyProcedureStates(String ticketCode,Integer state) {
		LambdaUpdateWrapper<TicketTask> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(TicketTask::getTicketInfoCode,ticketCode)
				      .set(TicketTask::getProcedureStates, state);
		update(updateWrapper);
	}
	
	@Override
	public void modifyProcedureStates(Long id, Integer state) {
		LambdaUpdateWrapper<TicketTask> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(TicketTask::getId,id)
				.set(TicketTask::getProcedureStates, state);
		update(updateWrapper);
	}
	
	@Override
	public boolean isCanStartOfTicket(String ticketCode) {
		boolean result = false;
		LambdaQueryWrapper<TicketTask> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TicketTask::getTicketInfoCode,ticketCode);
		List<TicketTask> taskList = list(queryWrapper);
		//质检人
		List<Long> inspectionList = ticketTaskDao.getPersonList(TicketConstants.TICKET_TASK_INSPECTION_PERSON);
		//报工人
		List<Long> reportList = ticketTaskDao.getPersonList(TicketConstants.TICKET_TASK_REPORT_PERSON);
		if(!taskList.isEmpty()){
			for(TicketTask task:taskList){
				if(!reportList.contains(task.getId())){
					return result;
				}
				if(TicketConstants.YES.equals(task.getInspectionStates())&&!inspectionList.contains(task.getId())){
				    return result;
				}
			}
			result = true;
		}
		return result;
	}
	
	/**
	 * 根据任务ID 查询不能操作的任务（结束|取消）
	 * @param taskIds
	 * @return  true 有可操作的   false  无
	 */
	private boolean inoperableTask(List<Long> taskIds){
		LambdaQueryWrapper<TicketTask> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(TicketTask::getId,taskIds);
		queryWrapper.and(wrapper-> wrapper.eq(TicketTask::getProcedureStates,TicketConstants.TICKET_STATUS_END)
				.or().eq(TicketTask::getProcedureStates,TicketConstants.TICKET_STATUS_CANCEL)	);
		List<TicketTask> taskList = list(queryWrapper);
		return taskList.isEmpty()?false:true;
	}
	
	
	
}
